<template>
  <div id="viewQuestionView">
    <a-row :gutter="[24, 24]">
      <a-col :md="12" :xs="24">
        <a-tabs default-active-key="question">
          <a-tab-pane key="question" title="题目">
            <a-card v-if="question" :title="question.title">
              <a-descriptions
                title="判题条件"
                :column="{ xs: 1, md: 2, lg: 3 }"
              >
                <a-descriptions-item label="时间限制">
                  {{ question.judgeConfig.timeLimit ?? 0 }}
                </a-descriptions-item>
                <a-descriptions-item label="内存限制">
                  {{ question.judgeConfig.memoryLimit ?? 0 }}
                </a-descriptions-item>
                <a-descriptions-item label="堆栈限制">
                  {{ question.judgeConfig.stackLimit ?? 0 }}
                </a-descriptions-item>
              </a-descriptions>
              <MdViewer :value="question.content || ''" />
              <template #extra>
                <a-space wrap>
                  <a-tag
                    v-for="(tag, index) of question.tags"
                    :key="index"
                    color="green"
                    >{{ tag }}
                  </a-tag>
                </a-space>
              </template>
            </a-card>
          </a-tab-pane>
          <a-tab-pane key="submitRecord" title="我的提交记录">
            <a-table style="text-align: center"
              :ref="tableRef"
              :columns="columns"
              :data="dataList"
              :pagination="{
                showTotal: true,
                pageSize: searchParams.pageSize,
                current: searchParams.current,
                total,
              }"
              @page-change="onPageChange"
            >
<!--              <template #judgeInfo="{ record }">-->
<!--                {{ JSON.stringify(record.judgeInfo) }}-->
<!--              </template>-->
              <!--判题状态-->
              <template #status="{ record }">
                <div v-if="record.status == 0" style="font-style: oblique"><strong>待判题</strong></div>
                <div v-if="record.status == 1" style="font-style: oblique"><strong>判题中</strong></div>
                <div v-if="record.status == 2" style="font-style: oblique"><strong>判题完成</strong></div>
                <div v-if="record.status == 3" style="font-style: oblique"><strong>判题失败</strong></div>
              </template>
              <!--执行用时-->
              <template #excuteTime="{ record }">
                <div style="text-align: center">{{ record.judgeInfo.time }} ms</div>
              </template>
              <!--消耗内存-->
              <template #excuteMemory="">
                <div style="text-align: center">N/A</div>
              </template>
              <template #createTime="{ record }">
                {{ moment(record.createTime).format("YYYY-MM-DD") }}
              </template>
              <template #optional="{ record }" >
                <div v-if="record.judgeInfo.message=='Wrong Answer'" style="text-align: center">
                  <a-button @click="$modal.info({ title:'详细信息', content:'内存消耗:'+record.judgeInfo.memory+'，时间消耗:'+record.judgeInfo.time })" type="primary" status="danger">解答错误</a-button>
                </div>
                <div v-if="record.judgeInfo.message=='Accepted'" style="text-align: center">
                  <a-button @click="$modal.info({ title:'详细信息', content:'内存消耗:'+record.judgeInfo.memory+'，时间消耗:'+record.judgeInfo.time })" type="primary" status="success">通过</a-button>
                </div>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="answer" title="答案">
            <CodeEditor
              :value="answer"
              :language="form.language"
              :handle-change="changeCode"
              :read-only= true
            />
          </a-tab-pane>
        </a-tabs>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form :model="form" layout="inline">
          <a-form-item
            field="language"
            label="编程语言"
            style="min-width: 240px"
          >
            <a-select
              v-model="form.language"
              :style="{ width: '320px' }"
              placeholder="选择编程语言"
            >
              <a-option>java</a-option>
              <a-option>cpp</a-option>
              <a-option>go</a-option>
              <a-option>html</a-option>
            </a-select>
          </a-form-item>
        </a-form>
        <CodeEditor
          :value="form.code as string"
          :language="form.language"
          :handle-change="changeCode"
        />
        <a-divider size="0" />
        <a-button type="primary" style="min-width: 200px" @click="doSubmit">
          提交代码
        </a-button>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect, withDefaults, defineProps } from "vue";
import message from "@arco-design/web-vue/es/message";
import CodeEditor from "@/components/CodeEditor.vue";
import MdViewer from "@/components/MdViewer.vue";
import {
  QuestionControllerService,
  QuestionSubmitAddRequest, QuestionSubmitQueryRequest,
  QuestionVO
} from "../../../generated";
import { useRouter } from "vue-router";
import moment from "moment/moment";

interface Props {
  id: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: () => "",
});

const router = useRouter();

const question = ref<QuestionVO>();
//提交记录
const tableRef = ref();
const dataList = ref([]);
const columns = [
  {
    title: "编程语言",
    dataIndex: "language",
  },
  // {
  //   title: "判题信息",
  //   slotName: "judgeInfo",
  // },
  // {
  //   title: "判题状态",
  //   dataIndex: "status",
  // },
  {
    title: "判题状态",
    slotName: "status",
  },
  {
    title: "执行用时",
    slotName: "excuteTime",
  },
  {
    title: "消耗内存",
    slotName: "excuteMemory",
  },
  {
    title: "创建时间",
    slotName: "createTime",
  },
  {
    title: '状态',
    slotName: 'optional'
  }
];
const searchParams = ref<QuestionSubmitQueryRequest>({
  questionId: undefined,
  language: undefined,
  pageSize: 10,
  current: 1,
});
const total = ref(0);
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};
const loadData = async () => {
  const res = await QuestionControllerService.getQuestionVoByIdUsingGet(
    props.id as any
  );
  if (res.code === 0) {
    question.value = res.data;
    console.log(question.value);
  } else {
    message.error("加载失败，" + res.message);
  }

  //提交记录
  const res2 = await QuestionControllerService.listQuestionSubmitByPageUsingPost(
    {
      ...searchParams.value,
      sortField: "createTime",
      sortOrder: "descend",
    }
  );
  if (res2.code === 0) {
    dataList.value = res2.data.records;
    total.value = res2.data.total;
  } else {
    message.error("加载失败，" + res2.message);
  }
};

const form = ref<QuestionSubmitAddRequest>({
  language: "java",
  code: "",
});

//答案
const answer = ref("");
answer.value = "public class Main {\n" +
  "    public static void main(String[] args) {\n" +
  "        int a = Integer.parseInt(args[0]);\n" +
  "        int b = Integer.parseInt(args[1]);\n" +
  "        System.out.println(\"结果:\" + (a + b));\n" +
  "    }\n" +
  "}\n"


/**
 * 提交代码
 */
const doSubmit = async () => {
  if (!question.value?.id) {
    return;
  }

  const res = await QuestionControllerService.doQuestionSubmitUsingPost({
    ...form.value,
    questionId: question.value.id,
  });
  if (res.code === 0) {
    message.success("提交成功");
  } else {
    message.error("提交失败," + res.message);
  }
  router.push({
    path: `/question_submit`,
  });
};

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

const changeCode = (value: string) => {
  form.value.code = value;
};
</script>

<style>
#viewQuestionView {
  max-width: 1400px;
  margin: 0 auto;
}

#viewQuestionView .arco-space-horizontal .arco-space-item {
  margin-bottom: 0 !important;
}
</style>
